<!--租客签约对话框-->
<template>
	<div class="renter-sign-dialog">
		<a-form ref="form" :model="entity" layout="vertical" :rules="renterContractRules(entity)">
			<a-typography-paragraph strong>
				<blockquote style="display: inline-block; margin-right: 10px">签约类型</blockquote>
				<a-radio-group v-model:value="entity.contractType" :disabled="isDisabled('contractType')" @change="changeContractType">
					<a-radio :value="1">个人合同</a-radio>
					<a-radio :value="4">框架协议</a-radio>
				</a-radio-group>
			</a-typography-paragraph>

			<a-radio-group v-model:value="entity.contractMedium" class="custom-radio-group" @change="onContractMediumChange">
				<a-space :size="12">
					<template v-for="item in contractTypes" :key="item.type">
						<a-radio-button :value="item.type" :disabled="item.type === 2 && !templates.length">
							<a-typography-paragraph>
								{{ item.title }}
								<small v-if="item.subTitle" v-color="{color: '#86909C'}">（{{ item.subTitle }}）</small>
							</a-typography-paragraph>
							<a-typography-paragraph v-color="{color: '#86909C'}">
								<small>{{ item.desc }}</small>
							</a-typography-paragraph>
							<a-form-item v-if="item.type === 2" name="econtractModelId" class="template-select-wrapper">
								<template #extra v-if="!templates.length && entity.houseId">请前往【企业>电子签约>合同模板】添加</template>
								<a-select
									v-model:value="entity.econtractModelId"
									v-bind="templateOption"
									:disabled="entity.contractMedium === 1"
									@change="handleSelectETemplate"
									@click.prevent>
									<template #notFoundContent>
										<a-empty :image="Empty.PRESENTED_IMAGE_SIMPLE">
											<template #description>
												暂无电子合同模板
												<br />
												请前往【企业>电子签约>合同模板】添加
											</template>
										</a-empty>
									</template>
								</a-select>
							</a-form-item>
						</a-radio-button>
					</template>
				</a-space>
			</a-radio-group>

			<a-typography-paragraph strong>
				<blockquote>房间信息</blockquote>
			</a-typography-paragraph>
			<a-form-item name="houseId" id="house-id" style="position: relative">
				<a-select
					:disabled="!!contract.houseId || [2, 3, 4].includes(contract.signType as number)"
					v-model:value="entity.houseId"
					v-bind="searchOption">
					<template v-if="loadings.search" #notFoundContent>
						<a-spin spinning tip="正在搜索，请稍候……" />
					</template>
				</a-select>
			</a-form-item>

			<a-typography-paragraph strong>
				<blockquote>承租人信息</blockquote>
			</a-typography-paragraph>
			<a-row :gutter="12" v-if="entity.renterInfo">
				<a-col :span="6">
					<a-form-item label="姓名：" :name="['renterInfo', 'name']">
						<a-input-group compact class="display-flex">
							<a-input
								v-model:value="entity.renterInfo.name"
								@blur="entity.renterInfo.name = entity.renterInfo.name?.trim()"
								:disabled="renterDisabled || enterPriseIdDisabled"
								placeholder="请输入姓名"
								style="flex: 1" />
							<a-form-item-rest>
								<a-radio-group
									v-model:value="entity.renterInfo.gender"
									:disabled="enterPriseIdDisabled"
									button-style="solid">
									<a-radio-button :value="1">男</a-radio-button>
									<a-radio-button :value="2">女</a-radio-button>
								</a-radio-group>
							</a-form-item-rest>
						</a-input-group>
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="手机号：" :name="['renterInfo', 'phone']">
						<a-input
							v-model:value.trim="entity.renterInfo.phone"
							@blur="entity.renterInfo.phone = entity.renterInfo.phone?.trim()"
							:disabled="renterDisabled || enterPriseIdDisabled"
							:maxlength="11"
							placeholder="请输入手机号" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="身份信息：" :name="['renterInfo', 'identityCard']">
						<a-input-group compact class="display-flex">
							<a-form-item-rest>
								<a-select
									v-model:value="entity.renterInfo.certificationType"
									:options="options.certificateTypes"
									:disabled="entity.contractMedium === 2 || enterPriseIdDisabled || entity.contractType === 4"
									@change="form?.clearValidate([['renterInfo', 'identityCard']])"
									style="width: 120px" />
							</a-form-item-rest>
							<a-input
								v-model:value.trim="entity.renterInfo.identityCard"
								@blur="entity.renterInfo.identityCard = entity.renterInfo.identityCard?.trim()"
								:disabled="enterPriseIdDisabled"
								:maxlength="18"
								placeholder="请输入证件号码"
								style="flex: 1" />
						</a-input-group>
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="证件照片：" :name="['renterInfo', 'frontImgUrl']">
						<a-button type="primary" block @click=";(visibles.certificate = true), (renter = entity.renterInfo)">
							<template v-if="entity.renterInfo.frontImgUrl || entity.renterInfo.rearImgUrl">
								<check-outlined />
							</template>
							<plus-outlined v-else />
						</a-button>
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="客户来源：">
						<a-select
							v-model:value="entity.renterInfo.customerResource"
							placeholder="请选择客户来源"
							:options="options.sources"
							allow-clear
							show-search
							option-filter-prop="name"
							:field-names="DEFAULT_FIELD_NAME" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="收付款账号：">
						<a-input-group compact class="display-flex">
							<a-form-item-rest>
								<a-select
									v-model:value="entity.renterInfo.paymentType"
									:options="paymentAccountList"
									placeholder="请选择类型"
									style="width: 100px" />
							</a-form-item-rest>
							<a-input
								v-model:value.trim="entity.renterInfo.paymentNo"
								placeholder="请输入账号"
								:maxlength="30"
								style="flex: 1" />
						</a-input-group>
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="紧急联系人：" :name="['renterInfo', 'emergencyName']">
						<a-input-group compact class="display-flex">
							<a-form-item-rest>
								<a-select
									v-model:value="entity.renterInfo.emergencyType"
									:options="relationshipList"
									placeholder="关系"
									style="width: 100px" />
							</a-form-item-rest>
							<a-input
								v-model:value="entity.renterInfo.emergencyName"
								@blur="entity.renterInfo.emergencyName = entity.renterInfo.emergencyName?.trim()"
								placeholder="请输入联系人姓名"
								style="flex: 1" />
						</a-input-group>
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="紧急联系人手机号：" :name="['renterInfo', 'emergencyPhone']">
						<a-input-group compact>
							<a-input
								v-model:value.trim="entity.renterInfo.emergencyPhone"
								@blur="entity.renterInfo.emergencyPhone = entity.renterInfo.emergencyPhone?.trim()"
								:maxlength="11"
								placeholder="请输入联系人手机号" />
						</a-input-group>
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="职业：">
						<a-select
							v-model:value="entity.renterInfo.profession"
							placeholder="请选择职业"
							:options="occupation"
							allow-clear
							show-search />
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="工作单位：">
						<a-input v-model:value.trim="entity.renterInfo.employer" placeholder="请输入工作单位" />
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="重点人群：">
						<a-select
							v-model:value="entity.renterInfo.keyGroupsType"
							placeholder="请选择重点人群"
							:options="options.keyGroups"
							allow-clear
							show-search
							option-filter-prop="name"
							:field-names="DEFAULT_FIELD_NAME" />
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="爱好：">
						<a-tooltip :title="hobbies.join('，') || '请选择爱好'" destroy-tooltip-on-hide>
							<a-select
								v-model:value="entity.renterInfo.interest"
								placeholder="请选择爱好"
								mode="multiple"
								:options="options.hobbies"
								allow-clear
								show-search
								max-tag-count="responsive"
								option-filter-prop="name"
								:field-names="DEFAULT_FIELD_NAME" />
						</a-tooltip>
					</a-form-item>
				</a-col>
				<a-col v-if="entity?.talentedPersonId" :span="6">
					<a-form-item label="人才类型:">
						<a-input v-model:value.trim="entity.talentedPersonTypeName" disabled />
					</a-form-item>
				</a-col>
			</a-row>

			<template v-if="entity.contractType === 4">
				<a-typography-paragraph strong>
					<blockquote>关联企业信息</blockquote>
				</a-typography-paragraph>
				<a-row :gutter="12">
					<a-col :span="8">
						<a-form-item label="承租企业信息：" :name="['renterInfo', 'enterPriseId']">
							<a-select
								:disabled="isDisabled()"
								v-model:value="entity.enterPriseId"
								show-search
								placeholder="请选择企业"
								allow-clear
								option-filter-prop="enterPriseName"
								:filter-option="filterOption"
								@change="selectEnterPriseId">
								<a-select-option v-for="item in options.enterpriseList" :key="item.id" :value="item.id">
									{{ item.enterPriseName }}/{{ item.enterPrisePhone }}
								</a-select-option>
							</a-select>
						</a-form-item>
					</a-col>
					<template v-if="entity.enterPriseId">
						<a-col :span="8">
							<a-form-item label="统一社会信用代码：">
								<a-input v-model:value="entity.societyCode" disabled placeholder="请输入社会信用代码" style="flex: 1" />
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="合作周期：" name="enterPriseTeamWorkId">
								<a-select
									:disabled="isDisabled('enterPriseTeamWorkId')"
									v-model:value="entity.enterPriseTeamWorkId"
									placeholder="请选择合作周期"
									@change="selectWorkId">
									<a-select-option v-for="item in options.teamworks" :key="item.id" :value="item.id">
										{{ item.beginTime + '至' + item.endTime }}
									</a-select-option>
								</a-select>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="协议优惠方案：" name="discountIds">
								<a-select
									:disabled="isDisabled('enterPriseTeamworkDiscountId')"
									v-model:value="entity.discountIds"
									mode="multiple"
									placeholder="请选择协议优惠方案"
									allow-clear
									@change="selectDiscountId">
									<template v-for="item in options.discount" :key="item.id">
										<a-select-option :value="item.id" :disabled="item.disabled">
											{{ item.discountName }}
											<template v-if="item.id">
												{{
													'[' +
													[
														item.beginTime + '至' + item.endTime,
														rentTypeMap[item.type],
														discountTypeMap[item.discountType] + item.discountScale + '%',
														item.stackable ? '可叠加' : '不可叠加',
														item.feeSubjects.map(o => o.name).join('/')
													]
														.filter(o => o)
														.join('/') +
													']'
												}}
											</template>
										</a-select-option>
									</template>
									<!-- 自定义优惠需要有权限才可以选择 -->
									<template v-if="store.hasPermissions(['mk_contract_charter_zjyhj', 'mk_contract_charter_yjyhj'])">
										<a-select-option value="-1" :option="{discountName: '自定义优惠'}">自定义优惠</a-select-option>
									</template>
								</a-select>
							</a-form-item>
						</a-col>
					</template>
				</a-row>
			</template>

			<a-typography-paragraph strong>
				<blockquote>
					同住人
					<a @click="onClickToAddTogether">
						<plus-circle-filled />
					</a>
				</blockquote>
			</a-typography-paragraph>
			<a-form-item v-if="entity.renterInfo?.togetherList?.length" :name="['renterInfo', 'togetherList']">
				<!--实现表单校验失败滚动到此处-->
				<a-input :bordered="false" style="position: absolute" />
				<a-form-item-rest>
					<vxe-table ref="togetherTable" :data="entity.renterInfo.togetherList" v-bind="togetherTableOption">
						<vxe-column min-width="120px" align="center">
							<template #header>
								<span v-color="{color: 'danger'}">*</span>
								姓名
							</template>
							<template #default="{row, rowIndex}">
								<a-input v-model:value.trim="row.name" :bordered="false" placeholder="请输入姓名" />
							</template>
						</vxe-column>
						<vxe-column min-width="120px" align="center">
							<template #header>
								<span v-color="{color: 'danger'}">*</span>
								手机号
							</template>
							<template #default="{row, rowIndex}">
								<a-input v-model:value.trim="row.phone" :bordered="false" placeholder="请输入手机号" />
							</template>
						</vxe-column>
						<vxe-column width="140px" align="center">
							<template #header>
								<span v-color="{color: 'danger'}">*</span>
								性别
							</template>
							<template #default="{row, rowIndex}">
								<a-radio-group v-model:value="row.gender">
									<a-radio :value="1">男</a-radio>
									<a-radio :value="2">女</a-radio>
								</a-radio-group>
							</template>
						</vxe-column>
						<vxe-colgroup align="center">
							<template #header>
								<span v-color="{color: 'danger'}">*</span>
								证件信息
							</template>
							<vxe-column width="120px" align="center" header-class-name="display-none">
								<template #default="{row, rowIndex}">
									<a-select v-model:value="row.certificationType" :bordered="false" :options="options.certificateTypes" />
								</template>
							</vxe-column>
							<vxe-column min-width="180px" align="center" header-class-name="display-none">
								<template #default="{row, rowIndex}">
									<a-input v-model:value.trim="row.identityCard" :bordered="false" placeholder="请输入证件号" />
								</template>
							</vxe-column>
						</vxe-colgroup>
						<vxe-column width="120px" align="center">
							<template #header>
								<span v-color="{color: 'danger'}">*</span>
								关系
							</template>
							<template #default="{row, rowIndex}">
								<a-select
									v-model:value="row.renterRelation"
									:bordered="false"
									:options="renterRelationList"
									placeholder="请选择关系" />
							</template>
						</vxe-column>
						<vxe-column width="60px" align="center">
							<template #header>
								<span v-if="entity.contractDecision?.frontImgUrl" v-color="{color: 'danger'}">*</span>
								证件
							</template>
							<template #default="{row, rowIndex}">
								<a @click=";(visibles.certificate = true), (renter = row)">
									<template v-if="row.frontImgUrl || row.rearImgUrl">
										<check-outlined />
									</template>
									<plus-outlined v-else />
								</a>
							</template>
						</vxe-column>
						<vxe-column title="操作" width="60px" align="center">
							<template #default="{row, rowIndex}">
								<a v-color="{color: 'danger'}" @click="onClickToRemoveRow(rowIndex, togetherTable as VxeTableInstance)">
									<svg-icon icon-class="trash" />
								</a>
							</template>
						</vxe-column>
					</vxe-table>
				</a-form-item-rest>
			</a-form-item>
			<a-typography-paragraph v-else style="margin-bottom: 2em" />
			<a-typography-paragraph strong>
				<blockquote>
					合同信息
					<span class="free-rang" v-if="isSignOwner">
						业主合同周期为{{ entity.minDate }}---{{ entity.maxDate }},请选择在周期内的日期
					</span>
				</blockquote>
			</a-typography-paragraph>
			<a-row :gutter="12">
				<a-col :span="5">
					<a-form-item label="成交方式/合同编号：" name="contractNo">
						<a-input-group compact class="display-flex">
							<a-form-item-rest>
								<a-select v-model:value="entity.signType" disabled :options="signTypeList" style="width: 80px" />
							</a-form-item-rest>
							<a-input v-model:value.trim="entity.contractNo" placeholder="请输入合同编号" style="flex: 1" />
						</a-input-group>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item name="beginTime">
						<template #label>
							<div class="display-flex">
								<span style="flex: 1">
									合同周期：
									<span class="free-rang" v-if="Number(entity.rentFreeDay) > 0">
										(免租周期：{{ freeRange[0] }}至{{ freeRange[1] }})
									</span>
								</span>
								<span v-if="entity.beginTime && entity.endTime" style="width: 170px">{{ cycleTip }}</span>
							</div>
						</template>
						<a-input-group compact class="display-flex">
							<a-range-picker
								:value="[entity.beginTime, entity.endTime]"
								:value-format="DATE_FORMAT.DATE"
								:disabled="[[2, 3, 4].includes(contract.signType as number)]"
								:disabled-date="disabledDate"
								style="flex: 1"
								@change="onDateChange" />
							<a-form-item-rest>
								<a-radio-group
									class="month-quick-radio-group"
									v-model:value="entity.leasePeriod"
									button-style="solid"
									@change="quickSelectDate">
									<a-radio-button :value="1">1月</a-radio-button>
									<a-radio-button :value="3">3月</a-radio-button>
									<a-radio-button :value="6">6月</a-radio-button>
									<a-radio-button :value="12">1年</a-radio-button>
								</a-radio-group>
							</a-form-item-rest>
						</a-input-group>
					</a-form-item>
				</a-col>
				<a-col :span="3">
					<a-form-item label="免租期天数：" name="rentFreeDay">
						<a-input-group compact>
							<a-button type="primary" :disabled="subDisabled" @click="subAddRentFreeDayFun('sub')">
								<template #icon><minus-outlined /></template>
							</a-button>
							<a-input
								v-model:value="entity.rentFreeDay"
								style="width: calc(100% - 64px)"
								readonly
								:min="0"
								:max="maxFreeNum"
								class="rent-free-day" />
							<a-button type="primary" :disabled="addDisabled" @click="subAddRentFreeDayFun('add')">
								<template #icon><plus-outlined /></template>
							</a-button>
						</a-input-group>
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="付款方式：">
						<a-input-group compact class="display-flex">
							<a-select
								v-model:value="entity.depositMonth"
								:options="mortgageMonthList"
								placeholder="请选择"
								style="flex: 1" />
							<a-select v-model:value="entity.periodMonth" :options="periodMonthList" placeholder="请选择" style="flex: 1" />
						</a-input-group>
					</a-form-item>
				</a-col>
				<a-col :span="4" >
					<a-form-item :label="`${entity.contractType === 4 ? '月租金':'租金单价'}：`" name="price">
						<div class="old-price" v-if="entity.contractType === 4 && house.actualPrice">原金额{{ house.actualPrice }}</div>
					<div style="display: flex;">

						<a-input-number
							class="contractRentType"

							v-model:value="entity.price"
							:min="0"
							:precision="2"
							:disabled="isDisabled('price')"
							placeholder="请输入租金" >
							<template #addonAfter>
									<a-radio-group
										v-if="entity.contractType!== 4"
										v-model:value="entity.contractRentType"
										:disabled="entity.contractType === 4 && house.actualPrice"
										button-style="solid"
										@change="changecontractRentType">
										<a-radio-button :value="1">月</a-radio-button>
										<a-radio-button :value="2">日</a-radio-button>
									</a-radio-group>
							</template>
						</a-input-number>
						</div>
					</a-form-item>
				</a-col>
				<a-col :span="3">
					<a-form-item label="押金：" name="deposit">
						<div class="old-price" v-if="entity.contractType === 4 && house.actualPrice">
							原金额{{ house.actualPrice * entity.depositMonth }}
						</div>
						<a-input-number
							v-model:value="entity.deposit"
							:min="0"
							:precision="2"
							:disabled="isDisabled('price') || contractDecision.disabledeposit"
							placeholder="请输入押金" />
					</a-form-item>
				</a-col>
				<a-col :span="7" >
					<a-form-item label="收租日设置：" name="payPatternValue">
						<a-input-group compact class="display-flex">
							<template v-if="entity.payPattern == 1">
								<a-input-number
									v-model:value="entity.payPatternValue"
									prefix="提前"
									:min="0"
									:precision="0"
									style="flex: 1; display: flex" />
							</template>
							<template v-else>
								<a-input-number
									v-model:value="entity.payPatternValue"
									prefix="固定"
									:min="1"
									:max="31"
									:precision="0"
									style="flex: 1; display: flex" />
							</template>
							<a-form-item-rest>
								<a-select
									v-model:value="entity.payPattern"
									:options="paymentMethodList"
									style="width: 200px"
									@change="entity.payPatternValue = null" />
							</a-form-item-rest>
						</a-input-group>
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="账单生成规则：">
						<a-select
							v-model:value="entity.cycleType"
							:options="waningMoonList"
							:disabled="entity.contractType === 4"
							placeholder="请选择账单生成规则" />
					</a-form-item>
				</a-col>
				<a-col :span="3">
					<a-form-item label="合同附件：">
						<a-button type="primary" block @click="visibles.attachment = true">
							<check-outlined v-if="entity.attachmentIds?.length" />
							<plus-outlined v-else />
						</a-button>
					</a-form-item>
				</a-col>
				<a-col :span="3">
					<a-form-item label="物业交割单：" name="delivery">
						<a-button type="primary" block :disabled="!entity.houseId" @click="visibles.delivery = true">
							<check-outlined v-if="delivery" />
							<plus-outlined v-else />
						</a-button>
					</a-form-item>
				</a-col>
				<a-col :span="24" v-if="entity.signType === 4">
					<a-form-item label="补充说明：" name="addExplanation">
						<a-textarea
							v-model:value.trim="entity.addExplanation"
							placeholder="请输入补充说明"
							:rows="4"
							show-count
							:maxlength="200" />
					</a-form-item>
				</a-col>
			</a-row>

			<!-- 新签续签 展示优惠活动 -->
			<template v-if="entity.contractType === 1">
				<a-typography-paragraph strong>
					<blockquote>优惠活动</blockquote>
				</a-typography-paragraph>
				<a-row>
					<a-col :span="24">
						<a-form-item label="可以使用活动：">
							<two-columns-select
								ref="twoColumnsSelectRef"
								v-model:value="entity.discountIds"
								v-bind="activityOptions"></two-columns-select>
						</a-form-item>
					</a-col>
					<br />
					<a-col :span="24">
						<a-form-item label="补充说明：" name="addExplanation">
							<a-textarea
								v-model:value.trim="entity.addExplanation"
								placeholder="请输入补充说明"
								:rows="4"
								show-count
								:maxlength="200" />
						</a-form-item>
					</a-col>
				</a-row>
			</template>

			<a-typography-paragraph strong>
				<blockquote>
					加收费用
					<a @click="onClickToAddOtherBill">
						<plus-circle-filled />
					</a>
				</blockquote>
			</a-typography-paragraph>
			<a-form-item v-if="entity.otherExpenses?.length" name="otherExpenses">
				<a-form-item-rest>
					<vxe-table ref="otherBillTable" :data="entity.otherExpenses" v-bind="otherBillTableOption">
						<vxe-column min-width="150px" align="center" class-name="fee-subject-change">
							<template #header>
								<span v-color="{color: 'danger'}">*</span>
								费用科目
								<a-popover v-if="contractDecision.shiftProperty" placement="bottomLeft">
									<template #content>
										<p v-if="contractDecision.shiftPropertyType === 1">物业费=房型物业费</p>
										<p v-if="contractDecision.shiftPropertyType=== 2">物业费=房间面积×物业费单价</p>
									</template>
									<question-circle-outlined :style="{color: 'rgba(0,0,0,0.85)'}" />
								</a-popover>
							</template>
							<template #default="{row, rowIndex}">
								<!-- <a-select v-model:value="row.feeSubjectId" :bordered="false" :options="options.feeSubjects" show-search option-filter-prop="name" :field-names="{label: 'name', value: 'id', options: 'metaList'}" placeholder="请选择费用科目" /> -->
								<a-select
									v-model:value="row.feeSubjectId"
									:disabled="(row.disabled && entity.signType === 4) || row.Feedisabled"
									:bordered="false"
									:options="row.isNew?options.useFeeSubjects:options.feeSubjects"
									@change="(value: string) => feeSubjectChange(value, row)"
									show-search
									option-filter-prop="name"
									:field-names="{label: 'name', value: 'id', options: 'metaList'}"
									placeholder="请选择费用科目" />
							</template>
						</vxe-column>
						<vxe-column min-width="150px" align="center" class-name="fee-subject-change">
							<template #header>
								<span v-color="{color: 'danger'}">*</span>
								付款方式
							</template>
							<template #default="{row, rowIndex}">
								<!-- <a-select v-model:value="row.periodMonth" :bordered="false" :options="periodMonthOptions" placeholder="请选择付款方式" /> -->
								<a-select
									v-model:value="row.periodMonth"
									:disabled="row.disabled"
									:bordered="false"
									:options="periodMonthOptions"
									placeholder="请选择付款方式" />
							</template>
						</vxe-column>
						<vxe-column min-width="150px" align="center">
							<template #header>
								<span v-color="{color: 'danger'}">*</span>
								金额
							</template>
							<template #default="{row, rowIndex}">
								<a-space>
									<template v-if="row.feeSubjectId === PropertyFeeSubjectId && contractDecision.shiftProperty && contractDecision.shiftPropertyType=== 2">
										{{ house.houseArea }} x {{ house.communityPropertyPrice }}
									</template>
									<a-input-number
										v-else
										v-model:value="row.price"
										:bordered="false"
										:controls="false"
										:disabled="row.Feedisabled"
										:min="0"
										:precision="2"
										placeholder="请输入金额" />
									<template v-if="[3,6,12,100].includes(row.periodMonth)">
										<span>x</span>
										<count-month :row="row" :entity="entity"/>
									</template>
								</a-space>
							</template>
						</vxe-column>
						<vxe-column title="操作" width="60px" align="center">
							<template #default="{row, rowIndex}">
								<a v-color="{color: 'danger'}" v-if="!(row.disabled  || row.Feedisabled)" @click="onClickToRemoveRow(rowIndex, otherBillTable)">
									<svg-icon icon-class="trash" />
								</a>
							</template>
						</vxe-column>
					</vxe-table>
				</a-form-item-rest>
				<!--实现表单校验失败滚动到此处-->
				<a-input disabled :bordered="false" style="position: absolute" />
			</a-form-item>

			<a-typography-paragraph v-else style="margin-bottom: 2em" />
			<a-typography-paragraph strong>
				<blockquote>签约信息</blockquote>
			</a-typography-paragraph>
			<a-row :gutter="12">
				<a-col :span="8">
					<a-form-item label="签约人：" name="signEmpId">
						<dept-emp-select
							v-model:dept-id="entity.signDeptId"
							v-model:emp-id="entity.signEmpId"
							@change="form.validate('signEmpId')" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="维护人：" name="maintainerId">
						<dept-emp-select v-model:emp-id="entity.maintainerId" disabled only-dept placeholder="请选择房源" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="签约时间：" name="signTime">
						<a-date-picker v-model:value="entity.signTime" placeholder="请选择签约日期" :value-format="DATE_FORMAT.DATE" />
					</a-form-item>
				</a-col>
			</a-row>
		</a-form>
		<teleport v-if="visibles.footer" to=".signing-dialog  .ant-modal-footer">
			<a-button type="primary" :disabled="disables.save" :loading="loadings.save" @click="dateInspect">保存并核对账单</a-button>
		</teleport>

		<!-- 附件上传 -->
		<file-upload-dialog v-model:visible="visibles.attachment" v-model:files="attachments" />
		<!-- 证件上传 -->
		<certificate-upload-dialog v-model:visible="visibles.certificate" :imgs="renter" />
		<!-- 账单预览 -->
		<renter-bill-preview-dialog v-model:visible="visibles.billPreview" :contract="entity" @success="onSubmitSuccess" />
		<!-- 物业交割单 -->
		<delivery-note
			v-model:visible="visibles.delivery"
			:id="entity.houseId"
			:signType="entity.signType"
			:contractId="entity.contractId"
			@success="data => (delivery = XEUtils.clone(data, true))"
			:delivery="delivery" />
		<!-- 通行授权弹窗 -->
		<access-authorization-dialog
			v-model:visible="visibles.accessAuth"
			:device-detail="deviceDetail"
			:hydropower="isShowHydropower"
			:is-resubmit="isResubmit"
			@success="cancel" />
	</div>
</template>

<script lang="ts" setup>
	import dayjs, {Dayjs} from 'dayjs'
	import {useStore} from '@/store'
	import XEUtils from 'xe-utils'
	import houseApi from '@/api/house-api'
	import settingApi from 'yuxin-base/src/api/setting-api'
	import {computed, createVNode, onMounted, reactive, ref, toRaw, watch, watchEffect} from 'vue'
	import {
		mortgageMonthList,
		occupation,
		paymentAccountList,
		paymentMethodList,
		periodMonthList,
		periodMonthOptions,
		relationshipList,
		renterRelationList,
		signTypeList,
		waningMoonList
	} from '@/utils'
	import {CheckOutlined, PlusCircleFilled, MinusOutlined, PlusOutlined, QuestionCircleOutlined} from '@ant-design/icons-vue'
	import CertificateUploadDialog from '@/components/common/certificate-upload-dialog.vue'
	import {Img} from 'yuxin-base/src/types'
	import DATE_FORMAT, {nowDate} from 'yuxin-base/src/utils/date'
	import {DEFAULT_FIELD_NAME, DIC_LABEL_MAP, DIC_PID_MAP, DIC_TAG_MAP} from 'yuxin-base/src/constant'
	import {VxeTableInstance, VxeTableProps} from 'vxe-table'
	import {Empty, FormInstance, Modal, message} from 'ant-design-vue'
	import {HouseDetail} from '@/interface/house'
	import {renterContractRules} from '@/rules/contract'
	import DeliveryNote from '@/components/contract/add-tenant-contract-dialog/delivery-note.vue'
	import FileUploadDialog from '@/components/common/file-upload-dialog.vue'
	import {
		getCommission,
		getContractTemplate,
		getCurEleAndWaterQuantity,
		getHouseDeliveryGetNoe,
		getRenterContractDetail,
		renterContractDeviceDetail,
		getPeriodTime,
		getEnterPriseLibraryListAll,
		register_renter
	} from '@/api/contract'
	import RenterBillPreviewDialog from '@/components/contract/tenant/renter-bill-preview-dialog.vue'
	import {defaultRenterContract, defaultRenterInfo, RenterContract, RenterContractDevice, RenterInfo} from '@/interface/contract'
	import {CERTIFICATION_TYPE_MAP} from 'yuxin-base/src/constant/index'
	import AccessAuthorizationDialog from '@/components/contract/add-tenant-contract-dialog/access-authorization-dialog.vue'
	import {isLockinEnv} from 'yuxin-base/src/utils'
	import twoColumnsSelect from '@/components/common/two-columns-select.vue'
	import {activityDiscountListByDeptId} from 'yuxin-base/src/api/activity-api'
	import fileApi from 'yuxin-base/src/api/file-api'
	import {SIGNTYPE} from '@/utils/state'
	import {discountTypeMap, rentTypeMap} from '@/constant/enterprise-customers'
	import CountMonth from './count-month'
	import {checkIdCard} from '@/utils/check'
	// import isSameOrBefore from 'dayjs/plugin/isSameOrBefore'
	// import isSameOrAfter from 'dayjs/plugin/isSameOrAfter'

	// dayjs.extend(isSameOrBefore)
	// dayjs.extend(isSameOrAfter)

	const store = useStore()

	const props = withDefaults(
		defineProps<{
			contract?: RenterContract
			isChooseProcedureFee?: boolean
			contractId?: string
			isResubmit?: boolean
			isConfiguration?: boolean
		}>(),
		{
			contract: {
				// @ts-ignore成交方式【1-新签,2-续签,3-转租,4-换房】，默认新签
				signType: 1
			},
			isConfiguration: false
		}
	)
	const loadings = reactive({
		save: false,
		search: false
	})

	const disables = reactive({
		save: false
	})

	const visibles = reactive({
		footer: false,
		attachment: false,
		certificate: false,
		delivery: false,
		billPreview: false,
		accessAuth: false
	})

	// 合同类型
	const contractTypes = [
		{
			type: 2,
			title: '电子合同',
			subTitle: '需短信邀请租客完成线上签约',
			desc: '适用于新签租客，采用CA电子合同并实名认证租客身份，具备法律效力'
		},
		{
			type: 1,
			title: '纸质合同',
			desc: '适用于已签租客纸质合同，将合同信息补录到系统中，方便统一管理合同及收支账单'
		}
	]

	const emits = defineEmits(['success'])

	// 表单内容
	const form = ref<FormInstance>()
	// 租客信息
	const renter = ref<RenterInfo>({})
	// 物业交割单
	const delivery = ref<any>()
	// 合同附件
	const attachments = ref<Img[]>([])
	// 房源信息
	const house = ref<HouseDetail>({})
	// 合同信息
	const entity = reactive<RenterContract>(defaultRenterContract())
	// 租客原始信息
	const originRenterInfo = ref<RenterInfo>({})
	// 免租期最大可填写
	const maxFreeNum = ref<number>(360)

	// 周期时长提示
	const cycleTip = ref<string>()

	//通行授权是否展示水电 续签则不展示
	const isShowHydropower = ref<boolean>(false)

	// 配置
	const signConfig = ref<any>(null)

	// 租客信息禁止编辑
	const renterDisabled = computed(() => house.value.status === 20 && house.value.houseBook !== null)

	// 框架协议续租禁止
	const enterPriseIdDisabled = computed(() => entity.contractType === 4 && entity.signType === 2)

	// 爱好
	const hobbies = computed(() => {
		const interest = (entity.renterInfo || {}).interest || []
		return options.hobbies.filter((item: any) => interest.includes(item.id)).map((item: any) => item.name)
	})

	/** 决策合同设置 */
	const contractDecision = ref<any>({
		// 紧急联系人
		emergencyName: false,
		// 物业交割单
		delivery: false,
		// 证件照片
		frontImgUrl: false,
		// 合同编号
		contractNo: false,
		disabledeposit: false,
		shiftProperty: false,
		shiftPropertyType: null,
		depositType: null
	})

	/** 业主合同周期 */
	const ownerPeriod = ref<any>({
		id: null
	})

	const isSignOwner = ref(false)

	const disabledDate = (current: Dayjs) => {
		// 需求修改，不对时间进行限制
		// if (isSignOwner.value) {
		// 	return current.isBefore(entity.minDate, 'day') || current.isAfter(entity.maxDate, 'day')
		// }

		// 个人合同
		if (entity.contractType === 1) {
			// 续、转、换合同开始时间禁用
			if ((entity.signType || 1) > 1) {
				return current.isBefore(entity.beginTime, 'day')
			} else {
				return false
			}
		}

		// 企业协议框架
		if (entity.contractType === 4) {
			// 表示正常
			let beginTime = currentTeamwork.value.beginTime
			let endTime = currentTeamwork.value.endTime
			if (entity.signType === 2) {
				// 表示续租
				const reletBeginTime = currentTeamwork.value.beginTime
				if (reletBeginTime || endTime) {
					return current.isBefore(beginTime, 'day') || current.isAfter(endTime, 'day')
				}
			} else {
				if (beginTime || endTime) {
					return current.isBefore(beginTime, 'day') || current.isAfter(endTime, 'day')
				}
			}
		}
	}

	watchEffect(() => {
		// 计算合同周期月数
		if (entity.beginTime && entity.endTime) {
			cycleTip.value = ''
			const beginTime = dayjs(entity.beginTime).subtract(1, 'day')
			const endTime = dayjs(entity.endTime)

			let years = endTime.diff(beginTime, 'year')
			let months = endTime.diff(beginTime, 'month')

			entity.leasePeriod = months
			if (years >= 1) {
				cycleTip.value = years + '年'
			}

			months = endTime.subtract(years, 'year').diff(beginTime, 'month')
			if (months >= 1) {
				cycleTip.value = (cycleTip.value || '') + months + '月'
			}

			const days = endTime.subtract(entity.leasePeriod, 'month').diff(beginTime, 'day')
			if (days >= 1) {
				cycleTip.value = (cycleTip.value || '') + days + '天'
			}

			if ([2, 3, 4].includes(props.contract?.signType as number)) {
				entity.rentFreeDay = 0
			}
		}
		// 附件列表
		entity.attachmentIds = attachments.value.map(o => o.id) as []
	})

	// 计算押金
	watch([() => entity.price, () => entity.depositMonth], (newVal, oldVal) => {
		// 框架协议时 租金改变不影响押金
		if (entity.contractType === 4 && newVal[0] !== oldVal[0]) {
			return
		}

		// 个人合同
		const price = contractDecision.value.disabledeposit ? entity.depositPrice : entity.price
		if (entity.contractType === 1) {
			entity.deposit = XEUtils.multiply(price, entity.depositMonth)
		}

		// 框架协议
		if (entity.contractType === 4) {
			// 自定义优惠的时候押金不做修改
			if (isCustomDiscount.value) return
			const price = contractDecision.value.disabledeposit ? entity.depositPrice :entity.discountIds?.length ? house.value.discountDeposit : house.value.actualPrice
			console.log('🚀 ~ file: renter-sign.vue:982 ~ watch ~ entity.discountIds?.length:', entity.discountIds?.length)
			entity.deposit = XEUtils.multiply(price, entity.depositMonth || 0)
		}
		//租金类型位日租金需要 * 30
		if(entity.contractRentType === 2 && !contractDecision.value.disabledeposit) {
			entity.deposit = XEUtils.multiply(entity.deposit, 30)
		}
	})

	// 加减免租期
	const subAddRentFreeDayFun = (type: any) => {
		if (type === 'add') {
			if (!entity.beginTime) {
				message.warn('请先选择合同周期')
				return
			}
			if (maxFreeNum.value > entity.rentFreeDay) {
				entity.rentFreeDay++
			}
		} else {
			if (entity.rentFreeDay > 0) {
				entity.rentFreeDay--
			}
		}
		blurFreeDay(type)
	}
	const changecontractRentType =(val)=>{
		const needReWriteDaily = props.contract?.signType === 2 && lastForm.value.contractRentType === 2
		const needReWriteMonth = props.contract?.signType === 2 && lastForm.value.contractRentType === 1
		if(val.target.value  === 2) {
			console.log(111);
			entity.price = needReWriteDaily ? lastForm.value.price : 0

		} else {
			entity.price = needReWriteMonth ? lastForm.value.price : 0
			// entity.price =props.contract?.signType !== 2 ? house.value.actualPrice : house.value.price
		}
	}
	// 监听加减免租期是否可点
	const subDisabled = ref<boolean>(true)
	const addDisabled = ref<boolean>(true)
	watch([() => entity.rentFreeDay, () => maxFreeNum.value], () => {
		if (Number(entity.rentFreeDay) <= 0) {
			subDisabled.value = true
		} else {
			subDisabled.value = false
		}
		if (Number(entity.rentFreeDay) >= maxFreeNum.value) {
			addDisabled.value = true
		} else {
			addDisabled.value = false
		}
	})

	// 计算免租周期
	const freeRange = ref<any>([])
	const blurFreeDay = (type: any) => {
		if (props.contract?.signType === 1) {
			//新签
			if (type === 'add') {
				entity.beginTime = dayjs(entity.beginTime).add(1, 'day').format(DATE_FORMAT.DATE)
				entity.endTime = dayjs(entity.endTime).add(1, 'day').format(DATE_FORMAT.DATE)
			} else {
				entity.beginTime = dayjs(entity.beginTime).subtract(1, 'day').format(DATE_FORMAT.DATE)
				entity.endTime = dayjs(entity.endTime).subtract(1, 'day').format(DATE_FORMAT.DATE)
			}
		}
	}
	watch([() => entity.rentFreeDay, () => entity.beginTime], () => {
		freeRange.value[0] = dayjs(entity.beginTime)
			.subtract(entity.rentFreeDay as number, 'day')
			.format('YYYY-MM-DD')
		freeRange.value[1] = dayjs(entity.beginTime).subtract(1, 'day').format('YYYY-MM-DD')
	})

	const init = async () => {
		getDics()

		await getContractDecision()

		const contract: RenterContract = props.contract || ({} as RenterContract)

		let renterInfo = contract.renterInfo || {}

		if (contract.otherExpenses && XEUtils.isString(contract.otherExpenses)) {
			try {
				contract.otherExpenses = JSON.parse(contract.otherExpenses || '[]')
			} catch (e) {
				contract.otherExpenses = []
			}
		}

		// @ts-ignore，过滤掉空值
		renterInfo = XEUtils.pick(renterInfo, v => v)
		originRenterInfo.value = renterInfo

		delete contract.renterInfo
		console.log('租客信息=========>', renterInfo)

		if (XEUtils.isString(renterInfo.interest) && XEUtils.trim(renterInfo.interest)) {
			renterInfo.interest = renterInfo.interest.split('/')
		}

		XEUtils.merge(entity, defaultRenterContract(), contract, {
			renterInfo,
			contractId: null,
			contractNo: null,
			signEmpId: store.currentUser.empId,
			signDeptId: store.currentUser.deptId,
			contractDecision: contractDecision,
			signTime: nowDate()
		})

		// 续租、合同重置、重新提交需要传contractId
		if (contract.contractId) {
			getContractDetail(contract.contractId)
			getDeliveryGetNoe(contract.contractId)
		} else if (contract.houseId) {
			entity.contractRentType = 1
			await getHouseRoom(contract.houseId)
			if (!props.isConfiguration) {
				getConfigurationF(contract.houseId)
			}
		}

		// 获取and回显 协议优惠框架 有id 转换续 有回显
		getEnterPriseLibraryListAllF(contract.contractId || contract.contractPid)

		// 转换房 免租期天数是否可以编辑
		if ([3, 4].includes(props.contract?.signType as number)) {
			let timeNew = dayjs().format('YYYY-MM-DD'),
				beginTime1 = dayjs(entity.beginTime).format('YYYY-MM-DD')
			if (dayjs(beginTime1).diff(timeNew, 'days') > 0) {
				//合同周期未生效
				maxFreeNum.value = dayjs(beginTime1).diff(timeNew, 'day')
				addDisabled.value = false
			}
		} else if (props.contract?.signType === 1) {
			maxFreeNum.value = dayjs(entity.endTime).diff(dayjs(entity.beginTime), 'days')
			console.log(maxFreeNum.value, 333)
			addDisabled.value = false
		}
	}

	/** 换房手续费手续费 根据签约类型换房 signType = 4 转租 signType = 3 转租  */
	const getCommissionCount = contractId => {
		if (entity.signType !== 4) return
		const from = {
			contractId,
			newPrice: entity.price,
			newStoreId: house.value.deptId,
			signType: entity.signType
		}
		getCommission(from).then(res => {
			if (res.data !== null && res.data !== 0) {
				const price = res.data
				// onClickToAddOtherBill()
				const metaList = options.feeSubjects.find(item => item.label === 'FEESUBJECT@PROCEDURE')?.metaList
				const feeSubjectId = metaList.find(item => item.tag === 'EXCHANGE_PROCEDURE_FEE')?.id
				entity.otherExpenses?.push({
					disabled: true,
					feeSubjectId,
					periodMonth: 99,
					price
				})
				otherBillTable.value?.reloadData(entity.otherExpenses as [])
			}
		})
	}
	const lastForm:any = ref({})
	// 获取合同详情
	const getContractDetail = (id: string) => {
		getRenterContractDetail(id).then(({data}: {data: RenterContract}) => {
			console.log(data, 'dda22')
			lastForm.value = data
			const renterInfo = data.renterInfo || {}

			const signType = props.contract?.signType || 1

			if (XEUtils.isString(renterInfo.interest) && XEUtils.trim(renterInfo.interest)) {
				renterInfo.interest = renterInfo.interest.split('/')
			}

			if (data.otherExpenses && XEUtils.isString(data.otherExpenses)) {
				try {
					data.otherExpenses = JSON.parse(data.otherExpenses || '[]')
				} catch (e) {
					data.otherExpenses = []
				}
			}else{
				data.otherExpenses = []
			}

			if (signType > SIGNTYPE.NEWSIGNING && !entity.reset && !entity.resubmit) {
				data.contractId = null
				data.contractPid = id
				data.signType = signType
				data.signTime = nowDate()
				data.contractNo = null
				data.addExplanation = null

				switch (signType) {
					case 2:
						// 续签周期计算
						data.beginTime = dayjs(data.endTime).add(1, 'day').format(DATE_FORMAT.DATE)
						if (props.contract?.endTime && props.contract.applyId) {
							data.endTime = props.contract.endTime
						} else {
							data.endTime = dayjs(data.beginTime).add(1, 'year').subtract(1, 'day').format(DATE_FORMAT.DATE)
						}
						break
					case 4:
						// 换房删除原房源id
						data.houseId = null
						// 换房周期计算，开始日期为操作日期第二天
						data.beginTime = dayjs(nowDate()).add(1, 'day').format(DATE_FORMAT.DATE)
						break
				}
			} else {
				// 签约申请、合同重置、重新提交合同ID不变
				entity.contractId = id
			}

			// @ts-ignore
			data = XEUtils.pick(data, v => v || v>-1)
			// @ts-ignore
			data.renterInfo = XEUtils.pick(renterInfo, v => v)

			XEUtils.merge(entity, data)
			//如果不是换房，且加收费用中有换房手续费，去掉换房手续费
			if (entity.signType !== 4 && entity.otherExpenses && entity.otherExpenses.length) {
				const metaList = options.feeSubjects.find(item => item.label === 'FEESUBJECT@PROCEDURE')?.metaList
				const feeSubjectId = metaList.find(item => item.tag === 'EXCHANGE_PROCEDURE_FEE')?.id
				console.log(entity.otherExpenses)
				let index = entity.otherExpenses.findIndex(o => o.feeSubjectId === feeSubjectId)
				if (index !== -1) {
					entity.otherExpenses.splice(index, 1)
				}
			}

			delete entity.house
			console.log('合同详情==============>', toRaw(data),data.contractRentType)
						// 续签 不展示 新签选择的活动
			// 重置 不展示 上次选择的活动 原因是活动可能已过期 如果要展示 需要过滤已过期的活动（endDate）
			// entity.discountIds = (data.discountDTOList || []).map(v => v.id)
			entity.deposit  = data.deposit
			entity.depositMonth = data.depositMonth

			getHouseRoom(entity.houseId as string)
			modificationTime()
			entity.contractRentType  = data.contractRentType
		})
	}

	// 获取物业交割单
	const getDeliveryGetNoe = (contractId: string) => {
		if (entity.resubmit) {
			const params = {
				id: contractId,
				type: 1
			}

			Promise.all([getHouseDeliveryGetNoe(params), fileApi.getFileList(contractId)])
				.then(([{data: deliveryData}, {data: attachments}]) => {
					delivery.value = deliveryData

					attachments.value = attachments.map(o => {
						o.name = o.fileOriginName
						return o
					})
				})
				.catch(error => {
					console.error(error)
				})
		}
	}
	// 查询房间是否绑定水电表
	const setEleAndWaterQuantity = () => {
		if (!deviceDetail.value.showWaterEle && !visibles.accessAuth) {
			cancel()
			return
		}
		getCurEleAndWaterQuantity({
			roomId: entity.houseId
		}).then((res: any) => {
			//绑定水电表切水电表为预付费
			if ((res.data.bindEleMater || res.data.bindClodWaterMater || res.data.bindHotWaterMater) && res.data.billGenerateMethod !== 3) {
				visibles.accessAuth = true
				isShowHydropower.value = true
			} else {
				isShowHydropower.value = false
			}
			if (!visibles.accessAuth) {
				cancel()
			}
		})
	}
	// 合同类型变更
	const onContractMediumChange = () => {
		form.value?.clearValidate()
		// 电子合同暂仅支持身份证
		if (entity.contractMedium === 2 && entity.renterInfo) {
			entity.renterInfo.certificationType = 1
		}
	}

	// 电子合同模板
	const templates = ref([])
	const templateOption = reactive({
		options: templates,
		size: 'small',
		bordered: false,
		showSearch: true,
		dropdownMatchSelectWidth: 300,
		optionFilterProp: 'contractTemplateName',
		placeholder: computed(() => (entity.houseId ? (templates.value.length ? '请选择模板' : '暂无电子合同模板') : '请先选择房源')),
		fieldNames: {label: 'contractTemplateName', value: 'id'}
	})

	// 房源搜索
	const searchOption = reactive<any>({
		options: [],
		allowClear: true,
		showSearch: true,
		optionFilterProp: 'address',
		placeholder: '请输入房源地址进行搜索',
		fieldNames: {label: 'address', value: 'houseRoomId'},
		style: {
			width: '100%'
		},
		onSearch(like: string) {
			if (like && like.trim()) {
				houseSearch(like)
			}
		},
		onSelect(value: string) {
			getHouseRoom(value)
			form.value?.clearValidate()
			clearActivity()
			getConfigurationF(value)
			entity.contractRentType = 1
		},
		onDeselect() {
			templates.value = []
			entity.contractMedium = 1
			entity.econtractModelId = null
			clearActivity()
		},
		getPopupContainer(triggerNode: HTMLDivElement) {
			return triggerNode ? triggerNode.parentNode : document.body
		}
	})

	/** 清空活动数据 */
	const clearActivity = (all = true) => {
		if (entity.discountIds && entity.discountIds.length) {
			entity.discountIds = []
			twoColumnsSelectRef.value?.onClear()
		}

		if (all) {
			if (activityOptions.leftOptions && activityOptions.leftOptions.length) {
				activityOptions.leftOptions = []
			}
			if (activityOptions.rightOptions && activityOptions.rightOptions.length) {
				activityOptions.rightOptions = []
			}
			if (activityOptions.talentAprOptions && activityOptions.talentAprOptions.length) {
				activityOptions.talentAprOptions = []
			}
		}
	}

	/** 优惠活动 options */
	const activityOptions = reactive({
		allowClear: true,
		/** 优惠活动数据 */
		leftOptions: [],
		/** 付款优惠数据 */
		rightOptions: []
	})
	/** 处理活动是否可以选 */
	const handlerActivityOptions = (count: number) => {
		activityOptions.leftOptions.forEach((item: any) => {
			if (Number(item.dataSource.useThreshold) > count) {
				item.disabled = true
			} else item.disabled = false
		})
		// activityOptions.leftOptions.sort(function(a, b) {
		// 	return a.disabled - b.disabled
		// })
		activityOptions.rightOptions.forEach((item: any) => {
			if ([1, 2].includes(entity.periodMonth as number)) {
				item.disabled = true
			} else {
				if (Number(item.dataSource.useThreshold) > count) {
					item.disabled = true
				} else item.disabled = false
			}
		})
		// activityOptions.rightOptions.sort(function(a, b) {
		// 	return a.disabled - b.disabled
		// })
	}
	// 合同租期改变 活动可选改变
	watch(
		() => entity.leasePeriod,
		(count: number | null | undefined) => count && handlerActivityOptions(count)
	)
	// 付款方式为 1 或者 2 不能使用优惠活动
	watch(
		() => entity.periodMonth,
		(count: number | null | undefined) => {
			// 付1 付2 不能使用 付款优惠
			if (count && [1, 2].includes(count)) {
				activityOptions.rightOptions.forEach((item: any) => {
					item.disabled = true
				})
			} else {
				handlerActivityOptions(entity.leasePeriod as number)
			}

			// 框架协议不进入此逻辑
			if (entity.contractType !== 4) clearActivity(false)
		}
	)

	type TwoColumnsSelectType = InstanceType<typeof twoColumnsSelect>
	/** 活动组件对象 */
	const twoColumnsSelectRef = ref<TwoColumnsSelectType | null>(null)
	watch(
		() => entity.discountIds,
		(list: string[] | undefined) => {
			// 回显
			const arr: any = []
			list?.forEach(id => {
				const left: any = activityOptions.leftOptions.find((v: any) => v.value === id)
				const right: any = activityOptions.rightOptions.find((v: any) => v.value === id)
				left && arr.push(left.dataSource)
				right && arr.push(right.dataSource)
			})
			entity.activitySelected = arr.filter((item, index, self) => {
				return self.findIndex(el => el.id === item.id) === index
			})
		}
	)
	/** 房间change 获取门店活动 */
	const getDeptActivityList = async (deptId: string, type: number) => {
		// const signType = type === 2 ? 2 : 1
		const signMap = {
			2: 2,
			// 换房
			4: 3
		}
		// 这个signType参数不是合同的signType 需要转换一下 = =
		const signType = XEUtils.has(signMap, type.toString()) ? signMap[type] : 1
		if (!deptId) return
		const left = await activityDiscountListByDeptId({
			deptId,
			type: 1,
			signType
		})
		activityOptions.leftOptions = left.data.map(v => ({
			label: v.name,
			value: v.id,
			checked: false,
			dataSource: v
		}))
		const right = await activityDiscountListByDeptId({
			deptId,
			type: 2,
			signType
		})
		activityOptions.rightOptions = right.data.map(v => ({
			label: v.name,
			value: v.id,
			checked: false,
			dataSource: v
		}))
		handlerActivityOptions(entity.leasePeriod ?? 12)
		// twoColumnsSelectRef.value?.onInit()？
	}

	const houseSearch = XEUtils.debounce((like: string) => {
		let params = {
			houseType: 0,
			like,
			current: 1,
			bizType: 1,
			size: 20,
			// hasHouseType: true,
			statusInCondition: [11]
		}

		// 签约未传入租客信息则搜索预定房源
		if (!originRenterInfo.value.name) {
			params.statusInCondition.push(20)
		}

		loadings.search = true
		houseApi
			.searchByAddress(params)
			.then((res: any) => {
				searchOption.options = res.data.records
			})
			.finally(() => (loadings.search = false))
	}, 300)

	const validateFee = (contractDecision,houseDetail) =>{
		const errorList = [
		]
		const {communityPropertyPrice,propertyPrice,depositPrice} = houseDetail
		const validatePorperty = contractDecision.value.shiftProperty && contractDecision.value.shiftPropertyType === 1
		const validateDeposit = contractDecision.value.disabledeposit
		const validatePorpertyByArea = contractDecision.value.shiftProperty && contractDecision.value.shiftPropertyType === 2
		if(validatePorperty && !propertyPrice) {
			errorList.push({name:'房型物业费'})
		}
		if(validatePorpertyByArea && !communityPropertyPrice) {
			errorList.push({name:'物业费单价'})
		}
		if(validateDeposit && !depositPrice) {
			errorList.push({name:'房型押金'})
		}
		const nameStr = errorList.map(e=>e.name).join('、')
		errorList.length && message.error(`未配置${nameStr}，无法操作，请先编辑房源进行配置`)
		return !errorList.length
	}
	// 当前签约房源
	const getHouseRoom = async (id: string) => {
		entity.houseId = id
		await houseApi.getHouseRoom(id).then(({data}: {data: HouseDetail}) => {
			console.log('房源详情==============>', toRaw(data))
			const validate = validateFee(contractDecision,data)
			if(!validate) {
				entity.houseId = null
				entity.otherExpenses = []
				return
			}

			if (data.houseBook && data.houseBook.bookStatus === 1) {
				disables.save = true
				house.value = {}
				XEUtils.assign(entity, defaultRenterContract())

				return Modal.warning({
					centered: true,
					title: '系统提示',
					content: '当前房源存在预定未支付记录，请先完成支付或作废后再进行签约'
				})
			} else {
				disables.save = false
			}

			house.value = data
			// 换房查询配置
			props.contract?.oldContractId && getCommissionCount(props.contract?.oldContractId)
			const signType = props.contract?.signType || 1
			if(signType !== 2) {
				entity.price = data.actualPrice
			}
			entity.basePrice = data.basePrice
			entity.housePid = data.housePid
			entity.houseAddress = data.fullAddress
			entity.maintainerId = data.stewardId


			// entity.talentedPersonTypeName = data?.talentedPersonTypeName || ''
			getTemplates(data.deptId as string)

			// housebizmode 1是代理
			if (data.houseBase?.houseBizMode === 1) {
				getPeriodTimeF(entity.housePid as string)
			}

			// const signType = props.contract?.signType || 1
			// 新签续签转租换房 查活动
			// if (signType !== 4) getDeptActivityList(data.deptId ?? '', signType)
			getDeptActivityList(data.deptId ?? '', signType)

			// 有id代表是签约申请转签约、合同重置
			if (signType === 1 && !entity.id) {
				entity.leasePeriod = 12

				if (data.houseBookId && data.houseBook) {
					entity.renterInfo = defaultRenterInfo()

					const houseBook = data.houseBook
					entity.renterInfo.name = houseBook.name
					entity.renterInfo.phone = houseBook.phone
					entity.renterInfo.gender = houseBook.gender || 1
					entity.leasePeriod = houseBook.contractMonth
					entity.renterInfo.identityCard = houseBook.certificateNo
					entity.renterInfo.certificationType = houseBook.certificateType || 1

					quickSelectDate()
				}
			}

			if (searchOption.options.length === 0) {
				searchOption.options = [
					{
						housePid: entity.housePid,
						houseRoomId: entity.houseId,
						address: entity.houseAddress
					}
				]
			}

			//计算优惠价格
			handleSetDeposit(data)
			handlePushPropertyPrice(data)
			discountCalculate(entity.price)
		})
	}

	// 根据房源部门获取电子合同模板
	const getTemplates = (deptId: string) => {
		entity.econtractModelId = null
		getContractTemplate({
			deptId,
			templateType: 1
		}).then(({data}) => {
			templates.value = data
			if (data && data.length) {
				entity.econtractModelId = data[0].id
				entity.authType = data[0].authType
			}
		})
	}

	/** 根据房源id获取业主合同周期 */
	const getPeriodTimeF = (houseId: string) => {
		getPeriodTime(houseId).then(({data}) => {
			console.log('🚀 ~ file: renter-sign.vue:1344 ~ getPeriodTime ~ data:', data)
			if (!data) {
				Modal.warning({
					centered: true,
					title: '系统提示',
					content: '该代理房源暂未签约业主合同'
				})
				return
			}
			isSignOwner.value = true
			ownerPeriod.value = data
			entity.minDate = data.minDate.substr(0, 10)
			entity.maxDate = data.maxDate.substr(0, 10)
		})
	}

	const options = reactive<any>({
		// 客户来源
		sources: [],
		// 爱好
		hobbies: [],
		// 重点人群
		keyGroups: [],
		// 费用科目
		feeSubjects: [],
		// 已生效的费用科目
		useFeeSubjects: [],
		// 证件类型
		certificateTypes: Object.keys(CERTIFICATION_TYPE_MAP).map(key => ({
			label: CERTIFICATION_TYPE_MAP[key],
			value: Number(key)
		})),
		// 企业列表
		enterpriseList: [],
		// 周期
		teamworks: [],
		// 折扣 协议
		discount: [],
		// 承租人联系人信息
		contacts: []
	})

	// 获取字典
	const getDics = (id: string) => {
		let action = id || [2, 4].includes(props.contract?.signType as number) ? settingApi.getDicListByPidAll : settingApi.getDicListByPid
		action(DIC_PID_MAP['CUSTOMER@HOBBY']).then(({data}) => (options.hobbies = data))
		action(DIC_PID_MAP['CUSTOMER@KEY_GROUPS']).then(({data}) => (options.keyGroups = data))
		action(DIC_PID_MAP['CUSTOMER@CHANNELSOURCE']).then(({data}) => (options.sources = data))

		settingApi.getDicListByLabel(DIC_LABEL_MAP['FEESUBJECT'], {isUse: null}).then(({data}) => (options.feeSubjects = data))
		settingApi.getDicListByLabel(DIC_LABEL_MAP['FEESUBJECT'], {isUse: 1}).then(({data}) => (options.useFeeSubjects = data))
	}

	/** 获取决策合同设置 */
	const getContractDecision = async () => {
		await settingApi.getDecisionList({module: 'CONTRACT'}).then(res => {
			// // 必填校验
			// const field_must = res.data.find(e=>e.bizPoint === 'CONTRACT_FIELD_MUST')
			// let field_must_ource = JSON.parse(field_must.value || '[]')
			// contractDecision.value.emergencyName = field_must_ource.includes(1) ? true : false
			// contractDecision.value.delivery = field_must_ource.includes(2) ? true : false
			// contractDecision.value.frontImgUrl = field_must_ource.includes(3) ? true : false
			// contractDecision.value.contractNo = field_must_ource.includes(4) ? true : false
			// 物业费生成配置
			const management_fee = res.data.find(e=>e.mark === 'MANAGEMENT_FEE_AUTO_GENERATE')
			let management_fee_source = JSON.parse(management_fee.value || '[]')
			contractDecision.value.shiftPropertyType = management_fee_source
			contractDecision.value.shiftProperty = management_fee.onOff === '1'
			// 合同押金生成配置
			const deposit_auto= res.data.find(e=>e.mark === 'CONTRACT_DEPOSIT_GENERATE')
			let deposit_auto_source = JSON.parse(deposit_auto.value || '[]')
			contractDecision.value.disabledeposit = deposit_auto_source === 2 ? true : false
			contractDecision.value.depositType = deposit_auto_source
		})
		await settingApi.getDecisionList({bizPoint: 'CONTRACT_FIELD_MUST', module: 'CONTRACT'}).then(res => {
			let source = JSON.parse(res.data[0]?.value || '[]')
			contractDecision.value.emergencyName = source.includes(1) ? true : false
			contractDecision.value.delivery = source.includes(2) ? true : false
			contractDecision.value.frontImgUrl = source.includes(3) ? true : false
			contractDecision.value.contractNo = source.includes(4) ? true : false
		})

	}
	const handleSetDeposit = async (houseDetail:any) =>{
		if (contractDecision.value.disabledeposit) {
			console.log(houseDetail.depositPrice,houseDetail,'asdadasd')

			entity.deposit = houseDetail.depositPrice
			entity.depositPrice = houseDetail.depositPrice
		}
	}
	const PropertyFeeSubjectId = ref({})
	const handlePushPropertyPrice = async (houseDetail:any) =>{
			const shouldPushFees = contractDecision.value.shiftProperty
			const shiftPropertyByRoom = contractDecision.value.shiftPropertyType === 1
			const shouldPushFeesByArea = contractDecision.value.shiftPropertyType === 2
			shouldPushFees && settingApi.getDicListByPidAll(DIC_PID_MAP['FEESUBJECT@SERVICE']).then(({data}) => {
				const current = data.find(e=>e.tag ==='HOUSE_PROPERTY_FEE') || {}
				const shouldPush = !entity.otherExpenses.some(e=>e.tag === 'HOUSE_PROPERTY_FEE' || e.feeSubjectId === current.id)
			PropertyFeeSubjectId.value = current.id
			if(shouldPush){
				entity.otherExpenses.push({
					feeSubjectId: current.id,
					periodMonth: null,
					price: shiftPropertyByRoom ? houseDetail.propertyPrice : houseDetail.houseArea * houseDetail.communityPropertyPrice,
					Feedisabled:true
				})
				setTimeout(()=>{
					// 为了显示出物业费文案，需要塞一个禁用的物业费选项
					const service = options.useFeeSubjects.find(v => v.label === 'FEESUBJECT@SERVICE')
					if (!service) return
					const property = service.metaList.find(v => v.tag === 'HOUSE_PROPERTY_FEE')
					if (!property) {
						service.metaList.push({...current, disabled: true})
					}
				},1000)
			} else {
				entity.otherExpenses.forEach(e=>{
					if(e.tag === 'HOUSE_PROPERTY_FEE'  || e.feeSubjectId === current.id) {
						e.Feedisabled = true
						e.price = shiftPropertyByRoom ? houseDetail.propertyPrice : houseDetail.houseArea * houseDetail.communityPropertyPrice
					}
				})
			}

			})
	}

	// 房间编辑表格配置
	const togetherTable = ref<VxeTableInstance>()
	const togetherTableOption = reactive<VxeTableProps>({
		size: 'mini',
		maxHeight: 200,
		border: true,
		cellStyle: {padding: 0},
		rowClassName: 'edit-table-row'
	})

	// 其它费用
	const otherBillTable = ref<VxeTableInstance>()
	const otherBillTableOption = reactive<VxeTableProps>({
		size: 'mini',
		maxHeight: 200,
		border: true,
		cellStyle: {padding: 0},
		rowClassName: 'edit-table-row'
	})

	// 添加同住人
	const onClickToAddTogether = () => {
		entity.renterInfo?.togetherList?.push({
			gender: 1,
			certificationType: 1
		})

		togetherTable.value?.reloadData(entity.renterInfo?.togetherList as [])

		console.log(entity.renterInfo?.togetherList)
	}

	// 添加其它费用
	const onClickToAddOtherBill = () => {
		entity.otherExpenses?.push({
			isNew: true
		})

		otherBillTable.value?.reloadData(entity.otherExpenses as [])
	}
	/** 换房手续费 转租手续费 */
	const targetFeeTagList = ['EXCHANGE_PROCEDURE_FEE', 'SUBLEASE_PROCEDURE_FEE']
	/** 加收费用 费用科目 change事件 */
	const feeSubjectChange = (value: string, row: any) => {
		let target: any = {}
		let tag = ''
		options.feeSubjects.forEach(item => {
			const obj = item.metaList.find(v => v.id === value)
			if (obj) {
				target = item
				tag = obj.tag
			}
		})
		if (target.label === 'FEESUBJECT@DEPOSIT') {
			// 付款方式 为 一次性付清 且 不可以修改
			row.periodMonth = 99
			row.disabled = true
		} else if (target.label === 'FEESUBJECT@PROCEDURE' && targetFeeTagList.includes(tag)) {
			// 手续大类  && entity.signType === 4
			row.periodMonth = 99
			row.disabled = true
		} else {
			row.disabled = false
			if (row.periodMonth === 99) {
				delete row.periodMonth
			}
		}
	}

	// 需要被禁用的费用科目大类集合
	// const targetFeeDisabledList = ['FEESUBJECT@DEPOSIT', 'FEESUBJECT@PROCEDURE']
	// 判断是否 押金大类 手续费大类
	const isFeeSubject = (list: any[], tId: string) => {
		let res = false
		list.forEach(item => {
			if (item.label === 'FEESUBJECT@DEPOSIT') {
				res = item.metaList.map(o => o.id).includes(tId)
			} else if (item.label === 'FEESUBJECT@PROCEDURE') {
				item.metaList.forEach(v => {
					if (targetFeeTagList.includes(v.tag) && item.metaList.map(o => o.id).includes(tId)) {
						res = Boolean(item.metaList.find(v => v.id === item.feeSubjectId))
					}
				})
			}
		})
		return res
	}
	// otherExpenses出参只有费用科目id字段 便利判断是否属于押金大类 或 手续费大类
	watchEffect(() => {
		entity.otherExpenses?.forEach(v => {
			if (isFeeSubject(options.feeSubjects, v.feeSubjectId)) {
				v.disabled = true
			}
		})
	})

	const onClickToRemoveRow = (index: any, tableInstance: VxeTableInstance) => {
		Modal.confirm({
			title: '系统提示',
			content: '删除后无法恢复，确定删除？',
			centered: true,
			icon: createVNode(QuestionCircleOutlined),
			onOk() {
				tableInstance.data?.splice(index, 1)
				tableInstance.reloadData(tableInstance.data as [])
			}
		})
	}

	const onDateChange = (dates: string[]) => {
		dates = dates || []
		if (dates[0] != entity.beginTime) {
			entity.rentFreeDay = 0
		}
		entity.beginTime = dates[0]
		entity.endTime = dates[1]

		if ([1].includes(props.contract?.signType as number)) {
			maxFreeNum.value = dayjs(entity.endTime).diff(dayjs(entity.beginTime), 'day')
		}
	}
	const modificationTime = () => {
		//框架协议加时间限制
		if (entity.contractType === 4 && dayjs(entity.endTime).isAfter(currentTeamwork.value.endTime)) {
			entity.endTime = currentTeamwork.value.endTime
			entity.maxDate = currentTeamwork.value.endTime
		}
	}
	const changeContractType =() =>{
		modificationTime()
		if(entity.contractType === 4){
			entity.contractRentType = 1
		}

	}
	const quickSelectDate = () => {
		entity.rentFreeDay = 0
		let beginDate = dayjs(entity.beginTime || nowDate())
		let endDate = beginDate.add(entity.leasePeriod || 12, 'month')

		if (beginDate.date() <= endDate.endOf('day').date()) {
			endDate = endDate.subtract(1, 'day')
		}

		// 需求修改，不对签约时间做限制
		// if (isSignOwner.value) {
		// 	if (beginDate.isBefore(entity.minDate, 'day')) {
		// 		endDate = entity.minDate
		// 	}
		// 	if (endDate.isAfter(entity.maxDate, 'day')) {
		// 		endDate = entity.maxDate
		// 	}
		// }

		entity.beginTime = beginDate.format(DATE_FORMAT.DATE)
		entity.endTime = endDate.format(DATE_FORMAT.DATE)

		form.value?.validate('beginTime')
		if (entity.contractType === 1) clearActivity(false)

		if ([1].includes(props.contract?.signType as number)) {
			maxFreeNum.value = dayjs(entity.endTime).diff(dayjs(entity.beginTime), 'day')
		}
		modificationTime()
	}

	//对合同周期做校验
	const dateInspect = () => {
		if (!entity.beginTime || !entity.endTime) {
			message.warn('请选择有效的合同周期')
			return
		}
		if (isSignOwner.value) {
			let label = signTypeList.filter(o => o.value == entity.signType)[0]?.label
			if (dayjs(entity.beginTime).isBefore(entity.minDate, 'day') || dayjs(entity.endTime).isAfter(entity.maxDate, 'day')) {
				Modal.confirm({
					title: '系统提示',
					content: `当前${label || '新签'}合同的合同周期与业主合同的周期发生冲突您确定继续进行${label || '新签'}操作吗？`,
					centered: true,
					icon: createVNode(QuestionCircleOutlined),
					onOk() {
						submit()
					}
				})
			} else {
				submit()
			}
		} else {
			submit()
		}
	}
	const handleSelectETemplate =(val,opt) =>{
		console.log(val,opt)
		const {authType} = opt
		entity.authType = authType
		}
	const check = async() =>{
		const isBestSign = entity.authType === 2
		if(isBestSign && entity.contractMedium === 2){
			loadings.save = true
			const res = await register_renter({
				personName:entity.renterInfo.name,
				personIdentityNo:entity.renterInfo.identityCard,
				personMobile:entity.renterInfo.phone
			}).finally(()=>{
				loadings.save = false
			})
			return res.data

		}
		return true
	}
	// 提交合同信息预览账单
	const submit = async() => {

		// 已签约业主合同 不能超过周期
		// 活动下拉框 折叠
		entity.signType !== 4 && twoColumnsSelectRef.value?.onFold()
		form.value
			?.validate()
			.then(async () => {
				// 部分手动检验
				const res = await check()
				if(!res){
					message.warn('上上签实名校验不通过，请检查')
					return
				}
				if (contractDecision.value.frontImgUrl && !entity?.renterInfo?.frontImgUrl) {
					message.warn('请上传证件照片')
					return
				}
				if (contractDecision.value.delivery && !delivery.value) {
					message.warn('请添加物业交割单')
					return
				}

				// 如果是协议框架 传原的租金 押金 自定义优惠传现有价格
				if (entity.contractType === 4) {
					entity.actualPrice = house.value.actualPrice
				} else {
					//个人合同清空企业信息
					entity.enterPriseId = null
					entity.enterPriseTeamWorkId = null
				}

				if (await isDisabledF()) return

				visibles.billPreview = true
				if (delivery.value) {
					entity.deliveryAddForm = delivery.value
					entity.deliveryAddForm.contractType = entity.contractType || 1
					entity.deliveryAddForm.deliveryType = 1
				}

				// entity.deliveryAddForm.meters = JSON.stringify(delivery.value.meters)
			})
			.catch(({errorFields}: any) => {
				form.value?.scrollToField(errorFields[0].name, {
					behavior: 'smooth'
				})
			})
	}

	// 合同签约成功
	const onSubmitSuccess = (value: any) => {
		if (typeof value !== 'boolean') {
			deviceAccessAuth(value)
		} else {
			cancel()
		}
	}
	const cancel = () => {
		house.value = {}
		delivery.value = null
		templates.value = []
		attachments.value = []
		searchOption.options = []
		emits('success')
		XEUtils.assign(entity, defaultRenterContract())
	}

	// 智能设备通行授权
	const deviceDetail = ref<RenterContractDevice>({} as RenterContractDevice)
	const deviceAccessAuth = (contractId: string) => {
		if (contractId) {
			renterContractDeviceDetail(contractId).then(({data}) => {
				data.renterInfos.forEach((item: any) => {
					item.accessAuthType = []
					item.lockAuthType = []
				})
				deviceDetail.value = data
				// showAccessLock 锁  showWaterEle 水电表 来自安全设置 是否展示
				//没有设备授权且是续租直接关闭弹窗，不展示水电
				if (!deviceDetail.value.showAccessLock) {
					if (props.contract?.signType !== 2 && isLockinEnv()) {
						//云丁没有设备授权，不是续租，查询水电是否清零
						setEleAndWaterQuantity()
						return
					}
					cancel()
					return
				}
				if (deviceDetail.value.hasLock || deviceDetail.value.hasAccess) {
					visibles.accessAuth = true
					if (props.contract?.signType !== 2 && isLockinEnv()) {
						//云丁没有设备授权，不是续租，查询水电是否清零
						setEleAndWaterQuantity()
					}
				} else {
					cancel()
				}
			})
		}
	}
	// 获取配置
	const getConfigurationF = (id: string) => {
				settingApi.getConfigurationData(id).then((res: any) => {
			console.log(res.data)
			if (res.data?.signConfig) {
				entity.contractMedium = res.data?.signConfig?.contractMedium
				if (entity.contractType !== 4) {
					entity.cycleType = res.data?.signConfig?.cycleType
				}
				entity.periodMonth = res.data?.signConfig?.periodMonth
				entity.depositMonth = res.data?.signConfig?.depositMonth
				entity.payPatternValue = res.data?.signConfig?.payPatternValue
				entity.payPattern = res.data?.signConfig?.payPattern
				entity.otherExpenses = res.data?.signConfig?.otherExpenses
			}
		})
	}

	/** ----- 关联企业信息 协议框架 start ----- */
	// 当前合作周期
	const currentTeamwork = computed(() => options.teamworks.find(o => o.id === entity.enterPriseTeamWorkId) || {})

	/**
	 * 合作周期是否和合同周期冲突 开始日期为合作周期开始日
	 */
	const intervalDay = ref(0)

	// 当前是否为自定义优惠
	const isCustomDiscount = ref<boolean>(false)

	const oldOnterPriseTeamworkDiscountId = ref()

	watch(
		() => entity.contractType,
		(value: any) => {
			clearActivity()

			// 企业框架合同 限制
			if (value === 4) {
				entity.cycleType = 1
				entity.renterInfo.certificationType = 1
			}
		}
	)

	watch(
		() => entity.discountIds,
		(value: any) => {
			if (entity.discountIds?.length === 0) {
				entity.price = house.value.actualPrice
				entity.deposit = contractDecision.value.disabledeposit ?  house.value.depositPrice : house.value.actualPrice
			}
		}
	)

	const filterOption = (input: string, option: any) => {
		return option.key.toLowerCase().indexOf(input.toLowerCase()) >= 0
	}

	const getEnterPriseLibraryListAllF = (id?: any) => {
		getEnterPriseLibraryListAll({}).then(({data}) => {
			options.enterpriseList = data

			// 转换续 重新提交 需要回显
			if (id && entity.contractType === 4) enterpriseInformation(data)

			if (props.isResubmit) {
				// contractDetails()
			}
		})
	}

	// 获取企业信息详情
	const enterpriseInformation = (data: any) => {
		const res = data.find((e: any) => e.id === entity.enterPriseId)
		console.log('🚀 ~ file: renter-sign.vue:1883 ~ enterpriseInformation ~ res:', res, entity.enterPriseId)
		entity.enterPriseId = res.id
		selectEnterPriseId(res.id)
	}

	// 选择企业
	const selectEnterPriseId = (value: string) => {
		const enterPrise = options.enterpriseList.find(e => e.id === value)

		// 回显各个字段
		entity.societyCode = enterPrise.societyCode
		options.contacts = enterPrise.contacts || []
		options.teamworks = enterPrise.teamworks || []

		// 折扣id和周期id 最优在最外层
		entity.enterPriseTeamWorkId = enterPrise.enterPriseTeamWorkId
		selectWorkId(entity.enterPriseTeamWorkId)
	}
	const selectWorkId = (value: any) => {
		if (!value) return
		const teamwork = options.teamworks.find(e => e.id === value) || {}

		options.discount = teamwork.discounts || []
		entity.discountIds = []

		checkData()
		selectDiscountId([])
	}

	const checkData = () => {
		let beginTime = currentTeamwork.value.beginTime
		let endTime = currentTeamwork.value.endTime
		if (
			(entity.beginTime as string) < beginTime ||
			(entity.beginTime as string) > endTime ||
			(entity.endTime as string) < beginTime ||
			(entity.endTime as string) > endTime
		) {
			entity.beginTime = null
			entity.endTime = null
			entity.leasePeriod = null
		}
		intervalDay.value = dayjs(endTime).diff(beginTime, 'month')

		// 假如是转租和换房使用默认传进入的时间
		if ([3, 4].includes(entity.signType as number)) {
			beginTime = entity.beginTime
		}

		if (intervalDay.value >= 6) {
			// 默认半年
			entity.beginTime = beginTime
			entity.endTime = dayjs(entity.beginTime)
				.add(entity.leasePeriod || 6, 'month')
				.add(-1, 'day')
				.format(DATE_FORMAT.DATE)
			entity.leasePeriod = 6
		} else {
			entity.leasePeriod = intervalDay.value || 6
			entity.beginTime = beginTime
			entity.endTime = endTime
		}
	}

	const selectDiscountId = (values: string[]) => {
		isCustomDiscount.value = values.includes('-1')

		// 清空或者选择自定义的时候押几重置
		if (values.length === 0 || isCustomDiscount.value) {
			entity.depositMonth = 1
		}

		// 所有优惠禁用状态
		options.discount.forEach(o => (o.disabled = isCustomDiscount.value))

		// 选择了自定义优惠
		if (isCustomDiscount.value) {
			// 移除所有已选优惠
			entity.discountIds = ['-1']
		} else if (values.length) {
			// 是否选择了可叠加优惠
			const stackable = options.discount.some(o => values.includes(o.id) && o.stackable)

			// 禁用相反的优惠
			options.discount.forEach(o => (o.disabled = stackable ? !o.stackable : !values.includes(o.id)))
		}

		discountCalculate()
	}

	/**
	 * 优惠计算
	 */
	const discountCalculate = (lastContractPrice) => {
		const {actualPrice} = house.value
		const contractDuration = dayjs(entity.beginTime).diff(entity.endTime,'day')
		const totalDaily = contractDuration * entity.price
		const isDailyPrice = entity.contractRentType === 2
		const dailyDeposit = entity.price * 30 // 压几后续会乘
		/**
		 * @desc 日/月租金取值 最终结算金额
		 */
		const finalPrice = isDailyPrice ? totalDaily: entity.price

		// todo 日租金押金怎么算
		const baseExtendPrice = isDailyPrice ?  dailyDeposit : (lastContractPrice || house.value.actualPrice)
		const baseDeposit = contractDecision.value.disabledeposit ?  house.value.depositPrice : baseExtendPrice

		entity.deposit = XEUtils.round(XEUtils.multiply(baseDeposit, entity.depositMonth || 0), 2)

		// 初始化押金1
		house.value.discountDeposit = baseDeposit

		// 自定义优惠取手动输入的金额，或初始化
		if (isCustomDiscount.value) {
			entity.price = isDailyPrice ? totalDaily : actualPrice
			entity.deposit = baseDeposit
			house.value.discountDeposit = baseDeposit

			// 无自定义押金优惠权限，押金优惠金额取原始金额
			if (!store.hasPermissions('mk_contract_charter_yjyhj')) {
				entity.deposit = baseDeposit
				house.value.discountDeposit = baseDeposit
			}
		}

		// 仅计算每月折优惠
		const discounts: any[] = options.discount.filter(o => entity.discountIds?.includes(o.id) && o.discountType === 1)

		// 按优惠力度排序，优惠力度越高越前
		discounts.sort((a, b) => a.discountScale - b.discountScale)
		//第一次拿租金或者押金原价计算，后面累加计算
		for (let i = 0; i < discounts.length; i++) {
			let discount = discounts[i]
			// 优惠费用范围
			const feeTags = discount.feeSubjects.map(o => o.tag)
			// todo
			let price = XEUtils.clone(actualPrice, true),
				deposit = XEUtils.clone(actualPrice, true)
			// 租金
			if (feeTags.includes(DIC_TAG_MAP['HOUSE_RENT'])) {
				// console.log('租金优惠计算')

				entity.price = XEUtils.multiply(i === 0 ? price : finalPrice, discount.discountScale / 100)
			}

			// // 押金
			if (feeTags.includes(DIC_TAG_MAP['HOUSE_DEPOSIT'])) {
				// console.log('押金优惠计算')
				entity.deposit = XEUtils.multiply(i === 0 ? deposit : entity.deposit, discount.discountScale / 100)
				house.value.discountDeposit = XEUtils.multiply(i === 0 ? deposit : entity.deposit, discount.discountScale / 100)
			}
		}

		// discounts.forEach(discount => {
		// 	// 优惠费用范围
		// 	const feeTags = discount.feeSubjects.map(o => o.tag)
		// 	let price = XEUtils.clone(actualPrice,true),deposit = XEUtils.clone(actualPrice,true)
		// 	// 租金
		// 	if (feeTags.includes(DIC_TAG_MAP['HOUSE_RENT'])) {
		// 		// console.log('租金优惠计算')

		// 		entity.price = XEUtils.multiply(price, discount.discountScale / 100)
		// 	}

		// 	// // 押金
		// 	if (feeTags.includes(DIC_TAG_MAP['HOUSE_DEPOSIT'])) {
		// 		// console.log('押金优惠计算')
		// 		entity.deposit = XEUtils.multiply(deposit, discount.discountScale / 100)
		// 	}
		// })
	}

	/** disabled判断 */
	const isDisabled = (type = 'default') => {
		let result = entity.signType === 2

		// 续签和换房不予许修改签约类型
		if (type === 'contractType') {
			result = entity.signType === 2 || entity.signType === 4 || !!entity?.talentedPersonId
		}

		if (type === 'enterPriseTeamWorkId') {
			result = entity.signType === 2
		}

		if (type === 'enterPriseTeamworkDiscountId') {
			if (entity.enterPriseTeamworkDiscountId === null) {
				result = false
			}

			// 组件清除操作
			let data = options.discount.find(e => e.id === oldOnterPriseTeamworkDiscountId.value)
			if (data === undefined && entity.enterPriseTeamworkDiscountId === undefined) {
				result = false
			}
		}

		if (type === 'price') {
			result = entity.contractType === 4 && entity.discountIds?.length && entity.discountIds[0] !== '-1'
		}

		return result
	}

	/** ----- 关联企业信息 end ----- */

	/** 重置使用 当前时间是否在合同周期内 且绑定能耗设备 */
	const inside = () => {
		// isBindEnergyDevice 0绑定 1未绑定 在获取的时候 因为是0被过滤了 所以反判断
		return (
			dayjs().isSameOrAfter(props.contract.beginTime, 'day') &&
			dayjs().isSameOrBefore(props.contract.endTime, 'day') &&
			entity.isBindEnergyDevice !== 1
		)
	}

	onMounted(() => {
		visibles.footer = true
		init()
	})

	// 82308字典修改 账单预览时判断选择的加收费用是否被禁用了
	//  82308字典修改 新签 来源重点人群 爱好 查询剩下 续签 ,换房，补签查询全部
	const isDisabledF = async () => {
		let temp = false
		let typesList: any = []
		let list: any = []
		let hobbies: any = []
		let keyGroups: any = []
		let sources: any = []

		let otherExpenses: any = XEUtils.clone(entity.otherExpenses, true) || []
		typesList = await settingApi.getDicListByLabel(DIC_LABEL_MAP['FEESUBJECT'], {isUse: 1})
		if (entity.contractId || [2, 3, 4].includes(entity.signType as number)) {
			hobbies = await settingApi.getDicListByPid(DIC_PID_MAP['CUSTOMER@HOBBY'])
			keyGroups = await settingApi.getDicListByPid(DIC_PID_MAP['CUSTOMER@KEY_GROUPS'])
			sources = await settingApi.getDicListByPid(DIC_PID_MAP['CUSTOMER@CHANNELSOURCE'])
		}
		typesList.data.forEach((e: any) => {
			list.push(...e.metaList)
		})
		list.forEach((e: any) => {
			otherExpenses?.forEach((o: any) => {
				if (e.id === o.feeSubjectId) {
					o.active = true
				}
				if (o.Feedisabled === true) {
					o.active = true
				}
			})
		})
		if (!otherExpenses?.every((e: any) => e?.active == true)) {
			temp = true
			return message.error('选项已禁用，请选择其他选项！')
		}
		if ([2, 3, 4].includes(entity.signType as number)) {
			let interest: any = []
			entity.renterInfo.interest &&
			entity.renterInfo.interest?.forEach((e: string) => {
				interest.push({
					id: e
				})
			})

			entity.renterInfo.interest &&
			hobbies.data?.forEach((e: any) => {
				// 相同表示没有禁用
				interest?.forEach((o: any) => {
					if (o.id === e.id) {
						o.active = true
					}
				})
			})

			if (
				(entity.renterInfo.interest && !interest?.every((i: any) => i.active == true)) ||
				(entity.renterInfo.customerResource && sources.data?.every((o: any) => o.id !== entity.renterInfo.customerResource)) ||
				(entity.renterInfo.keyGroupsType && keyGroups.data?.every((e: any) => e.id !== entity.renterInfo.keyGroupsType))
			) {
				temp = true
				return message.error('选项已禁用，请选择其他选项！')
			}
		}

		return temp
	}
</script>

<style lang="less">
	.teleport-footer {
		display: flex;
		justify-content: space-between;
		.ant-select {
			.ant-select-selector {
				border: none;
			}
		}
	}
</style>
<style lang="less" scoped>
	.free-rang {
		color: #ff4d4f;
		font-size: 12px;
	}
	.rent-free-day {
		text-align: center;
	}
	/deep/ .contractRentType .ant-input-number-group-addon{
	padding: 0;
	border: 0px;
	}

	.old-price {
		position: absolute;
		top: -30px;
		right: 0;
		color: blue;
	}
</style>
